#!/bin/bash

set -e
set -x

network=$(ip route | awk '/kernel/{printf $1}')

bypy download nfs-rpm.tgz

iplist_path=config
server_ip=$(grep server $iplist_path | awk -F, '{printf $2}')
server_dir=/srv/nfs
client_dir=/mnt/nfs_share
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    flag="${parts[3]}"
    
    if [ $address ];then
        sshpass -p$pass scp nfs-rpm.tgz $address:/opt/
        sshpass -p$pass ssh -n $address tar xf /opt/nfs-rpm.tgz -C /opt
        sshpass -p$pass ssh -n $address yum -y --disablerepo='*' localinstall /opt/nfs-rpm/*.rpm
        if [ $flag == 'server' ];then
            sshpass -p$pass ssh -n $address systemctl enable --now rpcbind nfs-server
            sshpass -p$pass ssh -n $address mkdir -p $server_dir
            sshpass -p$pass ssh -n $address chmod 777 $server_dir
            sshpass -p$pass ssh -n $address "cat <<EOF > /etc/exports
$server_dir        $network(rw,sync,no_subtree_check)
EOF"
            sshpass -p$pass ssh -n $address exportfs -arv
        else
            sshpass -p$pass ssh -n $address mkdir -p $client_dir
            sshpass -p$pass ssh -n $address mount -t nfs $server_ip:$server_dir $client_dir
            sshpass -p$pass ssh -n $address "cat <<EOF >> /etc/fstab
$server_ip:$server_dir $client_dir nfs defaults 0 0
EOF"
        fi
    fi
    
done < $iplist_path

set +x
set +e